package com.yonyougov.cruxtestcase.component;

import com.yonyougov.cruxtestcase.dto.BaseDto;
import com.yonyougov.cruxtestcase.dto.EnvQueryReqDto;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class ZWCDInvoke {
    private final RestTemplate restTemplate;
    @Value ("${drux.zwcd.url}")
    private String zwcdUrl;
    @Value ("${drux.zwcd.token}")
    private String token;

    public ZWCDInvoke(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String getBaseUrl(String envName) {
        EnvQueryReqDto envQueryReqDto = new EnvQueryReqDto();
        envQueryReqDto.setName(envName);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("token", token);
        httpHeaders.add("Content-Type","application/json");

        HttpEntity<EnvQueryReqDto> entity = new HttpEntity<>(envQueryReqDto, httpHeaders);

        ResponseEntity<BaseDto> dto = restTemplate.exchange(zwcdUrl + "/api/v2/env/query", HttpMethod.POST, entity, BaseDto.class);
        if (dto.getStatusCode() == HttpStatus.OK && dto.hasBody()) {
            BaseDto baseDto = dto.getBody();
            assert baseDto != null;
            if (CollectionUtils.isNotEmpty(baseDto.getDatas())) {
                String prefix = baseDto.getDatas().get(0).get("serverUrlPrefix").toString();
                prefix = prefix.endsWith("/") ? prefix.substring(0, prefix.length() - 1) : prefix;
                return prefix;
            }
        }
        return null;
    }
}
